package com.example.exam.ZhangFengHua;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.exam.R;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.google.gson.Gson;

import org.litepal.LitePal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;

import static androidx.constraintlayout.widget.Constraints.TAG;

public class Life_assistant extends Fragment {
    @BindView(R.id.iv_sx)
    ImageView ivSx;
    @BindView(R.id.tv_wd)
    TextView tvWd;
    @BindView(R.id.tv_qjwd)
    TextView tvQjwd;
    @BindView(R.id.LineChart)
    LineChart lineChart;
    private List<Life_LineChart_list> life_lineChart_lists = new ArrayList<>();
    private ArrayList<Entry> pointValues1 = new ArrayList<>();
    private ArrayList<Entry> pointValues2 = new ArrayList<>();
    private List<Book>book_list=new ArrayList<>();
    public Life_assistant() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_life_assistant, container, false);
        //牛油刀
        ButterKnife.bind(this, view);
        //创建数据库
        LitePal.getDatabase();
        Toast.makeText(getContext(), "创建成功", Toast.LENGTH_SHORT).show();
        //折线图设置数据
        initLineChrt();
        //给折线图设置样式
        initLineYs();
        return view;

    }
    String name[]={"昨天","今天","明天","周五","周六","周日"};
    private void initLineYs(){
        lineChart.animateXY(1000, 1000);
        //隐藏数据下的那个英文
        lineChart.setDescription(null);
        //=========================设置图例=========================
        // 像"□ xxx"就是图例
        Legend legend = lineChart.getLegend();
        //隐藏图例
        legend.setEnabled(false);
        //设置图例显示在chart那个位置 setPosition建议放弃使用了
        //设置垂直方向上还是下或中
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        //设置水平方向是左边还是右边或中
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        //设置所有图例位置排序方向
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //设置图例的形状 有圆形、正方形、线
        legend.setForm(Legend.LegendForm.CIRCLE);
        //是否支持自动换行 目前只支持BelowChartLeft, BelowChartRight, BelowChartCenter
        legend.setWordWrapEnabled(true);
        //=======================设置X轴显示效果==================
        //隐藏左边y轴
        YAxis leftAxis=lineChart.getAxisLeft();
        //不显示左Y轴的线
        leftAxis.setDrawAxisLine(false);
        //lineChart.getAxisLeft().setEnabled(false);
        leftAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getAxisLabel(float value, AxisBase axis) {
                return "";
            }
        });
        //隐藏右边y轴
        YAxis rightAxis=lineChart.getAxisRight();
        rightAxis.setEnabled(false);
        //设置x轴
        XAxis xAxis=lineChart.getXAxis();
        //x轴纵向分割线设置为不显示
        xAxis.setDrawGridLines(false);
        // X轴显示Value值的精度，与自定义X轴返回的Value值精度一致
        xAxis.setGranularity(1f);
        //x轴显示的数量
        xAxis.setLabelCount(6);
        //设置限制线的颜色
        lineChart.setBorderColor(Color.RED);
        xAxis.setGranularity(0);     //这个很重要
        //自定义x轴坐标
        xAxis.setValueFormatter(new IndexAxisValueFormatter() {
            @Override
            public String getAxisLabel(float value, AxisBase axis) {
                return name[(int) value];
            }
        });
    }
    //给折线图设置数据
    private void initLineChrt(){
        pointValues2=new ArrayList<>();
        pointValues1=new ArrayList<>();
        book_list=LitePal.findAll(Book.class);
        int x=1;
        for (Book book:book_list){
            Log.i(TAG, "ssa"+Float.parseFloat(book.getWd()));
            pointValues1.add(new Entry(x,Float.parseFloat(book.getWd())));
            pointValues2.add(new Entry(x, (float) (Math.random()*2*Float.parseFloat(book.getWd()))));
            x++;
        }
        LineDataSet set=new LineDataSet(pointValues2,"本周一周温度的变化");
        LineDataSet sety=new LineDataSet(pointValues1,"第二条折线的温度变化");
        //给折线图加颜色是3.1.0必须要加的
        set.setColor(Color.BLACK);
        sety.setColor(Color.BLUE);
        LineData set1=new LineData(set);
        //添加第二条折线数据
        set1.addDataSet(sety);
        lineChart.setData(set1);
        lineChart.invalidate();
        //---------

    }
    private void SQL(){
        Book book=new Book();
        book.setWd(life_lineChart_lists.get(0).getWendu()+"");
        book.save();
        List<Book> all = LitePal.findAll(Book.class);
        int size = all.size();
        //如果数据库里面的数据大于6条，则查询第一条，且删除id为第一条的数据，所以才能一直保持数据库内只有6条数据
        if(6<size){
            Book first = LitePal.findFirst(Book.class);
            LitePal.deleteAll(Book.class,"id=?",first.getId()+"");

        }
    }
    //数据库查询
    private void SQLCX(){
        List<Book>books=LitePal.findAll(Book.class);
        int size = books.size();
        for (Book book:books){
            Log.i(TAG, "SQLCX"+book.getWd()+"sf"+size);
        }
    }
    //点击按钮刷新
    @OnClick(R.id.iv_sx)
    public void onViewClicked() {
        initData();
        life_lineChart_lists = new ArrayList<>();
        SQLCX();
        //折线图设置数据
        initLineChrt();
    }
    public interface BlogService {
        @GET("aircondition")
        Call<ResponseBody> getlog();
    }
    public void initData() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http:hh1.me:5001/")
                .build();
        BlogService service = retrofit.create(BlogService.class);
        Call<ResponseBody> call = service.getlog();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Gson gson = new Gson();
                try {
                    Life_LineChart_list carlist = gson.fromJson(response.body().string(), Life_LineChart_list.class);
                    life_lineChart_lists.add(carlist);
                    int min = 0;
                    int max = 15;
                    Random random = new Random();
                    int num = random.nextInt(max) % (max - min + 1) + min;
                    tvWd.setText(life_lineChart_lists.get(0).getWendu() + "°");
                    tvQjwd.setText("今天：" + num + "-" + life_lineChart_lists.get(0).getWendu() + "摄氏度");
                    SQL();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }
}
